﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Toolkits.EntityFrameworkCore.Extensions;
using SD.Toolkits.Recursion.Tree;
using SlamDunk.MES.Domain.Entities.ResourceContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.ResourceContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.ResourceContext
{
    /// <summary>
    /// 人员类仓储实现
    /// </summary>
    public class PersonClassRepository : EFAggRootRepositoryProvider<PersonClass>, IPersonClassRepository
    {
        #region # 完整获取人员类 —— PersonClass SingleFully(Guid classId)
        /// <summary>
        /// 完整获取人员类
        /// </summary>
        /// <param name="classId">人员类Id</param>
        /// <returns>人员类</returns>
        public PersonClass SingleFully(Guid classId)
        {
            IQueryable<PersonClass> personClasses = base.Find(x => x.Id == classId).IncludeNavigationProperties();
            PersonClass personClass = personClasses.Single();

            return personClass;
        }
        #endregion

        #region # 深度获取人员类列表 —— ICollection<PersonClass> FindDeeply(string keywords...
        /// <summary>
        /// 深度获取人员类列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="parentNodeId">上级节点Id</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <returns>人员类列表</returns>
        public ICollection<PersonClass> FindDeeply(string keywords, Guid? parentNodeId, IList<Guid> facilityIds)
        {
            Expression<Func<PersonClass, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords)) &&
                    (parentNodeId == null || x.ParentNode.Id == parentNodeId);

            IQueryable<PersonClass> personClasses = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                personClasses = personClasses.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            ICollection<PersonClass> deepPersonClasses = personClasses.TailRecurseParentNodes();

            return deepPersonClasses;
        }
        #endregion

        #region # 获取根级人员类列表 —— ICollection<PersonClass> FindRoots()
        /// <summary>
        /// 获取根级人员类列表
        /// </summary>
        /// <returns>人员类列表</returns>
        public ICollection<PersonClass> FindRoots()
        {
            IQueryable<PersonClass> personClasses = base.Find(x => x.ParentNode == null);

            return personClasses.ToList();
        }
        #endregion
    }
}
